package com.atguigu.chapter06;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

import java.util.Arrays;
import java.util.List;
import java.util.Random;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/3/5 16:10
 */
public class Flink06_APPMarketingAnalysis {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // 1.读取数据
        DataStreamSource<MarketingUserBehavior> appDS = env.addSource(new AppData());

        // 2.处理数据
        // 按照 统计维度 分组：渠道、行为
        appDS
                .map(app -> Tuple2.of(app.getChannel() + "_" + app.getBehavior(), 1))
                .returns(Types.TUPLE(Types.STRING,Types.INT))
                .keyBy(r -> r.f0)
                .sum(1)
                .print();


        env.execute();
    }

    public static class AppData implements SourceFunction<MarketingUserBehavior> {

        private static volatile boolean isRunning = true;
        private List<String> userBehaviorList = Arrays.asList("DOWNLOAD", "INSTALL", "UNINSTALL", "UPDATE");
        private List<String> channelList = Arrays.asList("XIAOMI", "HUAWEI", "APPSTORE", "OPPO", "VIVO", "ZHUSHOU");

        @Override
        public void run(SourceContext<MarketingUserBehavior> ctx) throws Exception {
            Random random = new Random();
            while (isRunning) {
                ctx.collect(
                        new MarketingUserBehavior(
                                random.nextLong(),
                                userBehaviorList.get(random.nextInt(userBehaviorList.size())),
                                channelList.get(random.nextInt(channelList.size())),
                                System.currentTimeMillis())
                );
                Thread.sleep(1000L);
            }
        }

        @Override
        public void cancel() {
            isRunning = false;
        }
    }
}
